#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <string>
#include "log.hpp"

void Usage(std::string proc)
{
    std::cout << "usage:" << proc << "ip" << "port" << std::endl;
}

enum
{
    socket_error = 1,
    connect_error,
    send_error,
    recv_error,
};

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
    }
    std::string ip(argv[1]);
    uint16_t port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        Log(FATAL, "socket create error:%s", strerror(errno));
        exit(socket_error);
    }

    struct sockaddr_in addr;
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    // 连接
    int n = connect(sockfd, (sockaddr *)&addr, sizeof(addr));
    if (n < 0)
    {
        Log(FATAL, "connect false:%s", strerror(errno));
        exit(connect_error);
    }
    while (true)
    {
        // 发消息
        std::cout<<"please enter# ";
        std::string line;
        std::getline(std::cin, line);
        n=send(sockfd, line.c_str(), line.size(), 0);
        if(n<0)
        {
            Log(ERROR,"send false:%s",strerror(errno));
            exit(send_error);
        }
        else
        {
            Log(DEBUG,"send success");
        }
        // 收消息
        char inbuffer[1024];
        n=recv(sockfd, inbuffer, sizeof(inbuffer), 0);
        if(n<0)
        {
            Log(ERROR,"recv false:%s",strerror(errno));
            exit(recv_error);
        }
        else
        {
            inbuffer[n]='\0';
            //Log(DEBUG,"recv success:%s",inbuffer);
            std::cout<<inbuffer<<std::endl;
        }
    }

    return 0;
}
